package com.skynet.supervision.handler;

import com.skynet.supervision.utils.ObjectUtils;
import org.apache.ibatis.type.LocalDateTimeTypeHandler;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

@Component
public class DbLocalDateTimeTypeHandler extends LocalDateTimeTypeHandler {


    @Override
    public LocalDateTime getResult(ResultSet rs, String columnName) throws SQLException {
        Object object = rs.getObject(columnName);
        System.out.println(object);
        if (ObjectUtils.isEmpty(object)) {
            return null;
        }
        if (object instanceof java.sql.Timestamp) {
            return LocalDateTime.ofInstant(((Timestamp) object).toInstant(), ZoneId.systemDefault());
        } else if (object instanceof java.sql.Date) {
            return LocalDateTime.ofInstant(((java.sql.Date) object).toInstant(), ZoneId.systemDefault());
        } else if (object instanceof Long) {
            return LocalDateTime.ofInstant(Instant.ofEpochSecond((Long) object), ZoneId.systemDefault());
        }
        return super.getResult(rs, columnName);
    }
}
